#include "serialcore.h"
#include <QDateTime>
#include <QApplication>
#include <QDebug>
SerialCore::SerialCore()
{
    connect(&mPort,SIGNAL(readyRead()),this,SLOT(Slot_ReadyRead()));
}

void SerialCore::SetSerialPortInfo(QString Name, int Baudrate, QSerialPort::DataBits dataBit, QSerialPort::StopBits stopBit, QSerialPort::Parity parity)
{
    mPort.setPortName(Name);
    mPort.setBaudRate(Baudrate);
    mPort.setDataBits(dataBit);
    mPort.setStopBits(stopBit);
    mPort.setParity(parity);
}

void SerialCore::Open()
{
    mPort.open(QSerialPort::ReadWrite);
}

void SerialCore::Write(QByteArray writeBuf)
{
    mPort.write(writeBuf);
}

void SerialCore::Close()
{
    mPort.close();
}

void SerialCore::Read(int shouldReadLength,QByteArray &readBuf)
{
    QByteArray ret;
    ret.clear();
    QDateTime now=QDateTime::currentDateTime();
    while (now.msecsTo(QDateTime::currentDateTime())<mSecondTimeOut&&readBuf.length()<shouldReadLength)
    {
        QApplication::processEvents();
        if(readyReadVector.count()>0)
        {
            QByteArray temp=mPort.readAll();
            readBuf.append(temp);
        }
    }
}

void SerialCore::Slot_ReadyRead()
{
    readyReadVector.append(1);
}
